package org.batatasframework.common;

import cn.bonoon.kernel.util.StringHelper;

/**
 * 对字符串的金额进行解析处理
 * 
 * 解析后的货币单位都是"元"
 * @author jackson
 *
 */
public class CurrencyResolver extends NumberResolver{

	/** 金额是允许为空的，即没填写的情况 */
	private Double amount;

	private static char[] CAPITAL_UNITS = {'拾', '佰', '仟', '万', '亿'};
	private static char[] CHINESE_UNITS = {'十', '百', '千', '万', '亿'};
	private static int[] RATES = {10, 100, 1000, 10000, 100000000};
	
	public static CurrencyResolver valueOf(String source){
		return new CurrencyResolver(source);
	}
	
	protected CurrencyResolver(String source) {
		super(source);
	}

	@Override
	public boolean parse() {
		if(null == source){
			message = "金额为空";
			return false;
		}
		
		char[] chs = source.toCharArray();
		StringBuilder strNum = new StringBuilder();
		int lastNumberIndexOf = 0;  //最后一个数值的位置，也就是说，如果后面还有值的，则应该是单位了，如：元、万元、亿等单位
		for(int i = 0; i < chs.length; i++){
			//处理小数点的情况
			if(chs[i] == '.'){
				if(strNum.length() == 0){
					strNum.append('0');
				}
				strNum.append('.');
			}else if(readNumber(chs[i], strNum)){
				lastNumberIndexOf = i;
			}
		}
		
		amount = StringHelper.toDouble(strNum.toString());
		if(null != amount){
			if(amount > 0D){
				//有可能是"xxx万元"，"xxx元"等情况
				for(int i = lastNumberIndexOf + 1; i < chs.length; i++){
					char ch = chs[i];
					for(int j = 0; j < RATES.length; j++){
						if(ch == CAPITAL_UNITS[j] || ch == CHINESE_UNITS[j]){
							amount *= RATES[j];
						}
					}
				}
			}
		}else if(chs.length > 0){
			//输入的金额格式无法被解析的情况
			message = "金额格式不正确，无法识别";
			return false;
		}
		return true;
	}
	
	public Double getAmount() {
		return amount;
	}
	
	public double toAmount(){
		return null == amount ? 0D : amount;
	}
}
